package com.demo.config.sharding;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shardingsphere.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.hint.HintShardingValue;

import java.util.Collection;

/**
 * 强制分配分片策略
 */
@Slf4j
public class HintShardingStrategy implements HintShardingAlgorithm<String> {
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, HintShardingValue<String> shardingValue) {
        log.info("强制分配分片策略，表:{}，ShardingValue:{}", availableTargetNames, shardingValue);
        Collection<String> values = shardingValue.getValues();
        if (CollectionUtils.isNotEmpty(values)) {
            for (String dataSourceName : availableTargetNames) {
                for (Object value : values) {
                    if (StringUtils.equalsAnyIgnoreCase((String) value, dataSourceName)) {
                        return Lists.newArrayList(dataSourceName);
                    }
                }
            }
        }
        return availableTargetNames;
    }
}
